import 'package:flutter/material.dart';
import 'package:flutter_demo/components/article_card.dart';
import 'package:flutter_demo/models/article_model.dart';
import 'package:flutter_demo/services/article_service.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class ArticlePage extends StatefulWidget {
  @override
  _ArticlePageState createState() => _ArticlePageState();
}

class _ArticlePageState extends State<ArticlePage>
    with AutomaticKeepAliveClientMixin {
  // 下拉刷新控制器
  EasyRefreshController _easyRefreshController;

  List<ArticleItem> _articleList = ArticleList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool error = false;
  String errorMsg;

  @override
  void initState() {
    super.initState();

    print('song初始化了');

    _easyRefreshController = EasyRefreshController();

    _getArticles();
  }

  // 获取数据
  Future _getArticles({bool push = false}) async {
    try {
      // 获取数据
      Map<String, dynamic> result =
          await ArticleService.getArticles(page: page);
      // print(result);
      // 将数据转为实体类
      ArticleList songListModel = ArticleList.fromJson(result['data']);

      setState(() {
        hasMore = page * limit < result['total'];
        page++;

        if (push) {
          _articleList.addAll(songListModel.list);
        } else {
          _articleList = songListModel.list;
        }
      });
    } catch (e) {
      print(e);

      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    }
  }

  // 下拉刷新
  Future _onRefresh() async {
    page = 1;
    await _getArticles();
    // 完成刷新
    _easyRefreshController.finishRefresh();
    // 重置刷新组件插件状态
    _easyRefreshController.resetLoadState();
  }

  // 上拉加载
  Future _onLoad() async {
    if (hasMore) {
      await _getArticles(push: true);
    }
    // 完成加载
    _easyRefreshController.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      controller: _easyRefreshController,
      enableControlFinishLoad: true,
      enableControlFinishRefresh: true,
      onLoad: _onLoad,
      header: ClassicalHeader(),
      footer: ClassicalFooter(),
      onRefresh: _onRefresh,
      child: ListView.builder(
        itemCount: _articleList.length,
        itemBuilder: (BuildContext context, int index) {
          return Column(
            children: [
              SizedBox(height: 8),
              ArticleCard(articleItem: _articleList[index])
            ],
          );
        },
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
